package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.ClueTrackRecordType;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.clue.ClueDO;
import com.qk.dto.clue.*;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import com.qk.vo.clue.ClueVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


/**
 * @author diva
 * @date 2025/10/13 16:55
 * @ProjectName
 */
@Slf4j
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;
    @Autowired
    private BusinessMapper businessMapper;

    @Override
    public void addClue(ClueDTO dto) {
        if(ObjectUtil.isEmpty(dto.getPhone())||ObjectUtil.isEmpty(dto.getChannel())){
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }
        Clue clue =BeanUtil.copyProperties(dto, Clue.class);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        this.save(clue);
    }

    @Override
    public PageResult<ClueDO> clueList(ClueListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<ClueDO> list = this.baseMapper.selectByPage(dto);
        Page<ClueDO> page = (Page<ClueDO>) list;
        return PageResult.<ClueDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Override
    public ClueVO getClueInfoById(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        if(ObjectUtil.isEmpty(clue)){
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }
        Integer userId = clue.getUserId();
        User user = userMapper.selectById(userId);
        List<ClueTrackRecord> clueTrackRecords =
                clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class)
                .in(ClueTrackRecord::getClueId, id)
        );
        ClueVO cluevo=BeanUtil.copyProperties(clue, ClueVO.class);
        List<ClueVO.ClueTrackRecordVO> list = clueTrackRecords.stream().map(item ->{
            ClueVO.ClueTrackRecordVO vo = BeanUtil.copyProperties(item, ClueVO.ClueTrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        cluevo.setTrackRecords(list);
        return cluevo;
    }
    @Transactional
    @Override
    public void updateClueInfoById(UpdateClueInfoDTO dto) {
        log.info("==============Controller中的updateClueInfoById处理线程名称是={}",Thread.currentThread().getName());
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());
        if(dto.getStatus() == ClueStatusConstants.WAIT_FOLLOW_UP){
            clue.setStatus(ClueStatusConstants.FOLLOWED_UP);
        }
        this.baseMapper.updateById(clue);

        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setType(ClueTrackRecordType.NORMAL);
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        this.clueTrackRecordMapper.insert(clueTrackRecord);

    }

    @Transactional
    @Override
    public void toBusiness(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(ClueStatusConstants.CONVERTED_TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);

        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId(null);
        business.setUpdateTime(LocalDateTime.now());
        business.setCreateTime(LocalDateTime.now());
        business.setNextTime(null);
        business.setUserId(null);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setClueId(id);
        this.businessMapper.insert(business);

    }

    @Override
    public PageResult<Clue> cluePool(CluePoolDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Clue> list = this.baseMapper.selectByPool(dto);
        Page<Clue> page = (Page<Clue>) list;
        return PageResult.<Clue>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Transactional
    @Override
    public void toFalse(Integer id, MarkFalseClueDto dto) {
        //2. 添加一条跟进记录，跟进的类型type为0，表示伪线索；上图中的伪线索的原因对应于 falseReason ;  备注说明对应于跟进记录 record 。（subject，level，nexttime没有值，就不需要指定）
        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(ClueStatusConstants.FAKE_CLUE);
        clue.setUpdateTime(LocalDateTime.now());
        clue.setNextTime(null);
        this.baseMapper.updateById(clue);


        ClueTrackRecord clueTrackRecord = new ClueTrackRecord();
        clueTrackRecord.setClueId(clue.getId());  // 设置关联的线索ID
        clueTrackRecord.setFalseReason(dto.getReason());  // 设置伪线索原因
        clueTrackRecord.setRecord(dto.getRemark());  // 设置备注说明
        clueTrackRecord.setType(ClueTrackRecordType.FAKE);  // 类型为0，表示伪线索
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());  // 设置当前操作用户ID
        clueTrackRecord.setLevel(clue.getLevel());
        clueTrackRecord.setSubject(clue.getSubject());
        clueTrackRecord.setCreateTime(LocalDateTime.now());  // 设置创建时间

        this.clueTrackRecordMapper.insert(clueTrackRecord);

    }


}
